import axios from 'axios'
import { THREE } from 'threebox-plugin'
import geojsonExtent from '@mapbox/geojson-extent'

class LandManager {
  constructor(vueInstance) {
    this.map = vueInstance.map
    this.tb = vueInstance.threeBoxLayer.tb
    this.vueInstance = vueInstance
    this.data = []
    this.extrusions = []
    this._getData()
  }

  _getData() {
    axios.get('./data/landPolygon.geojson').then(res => {
      this.data = res.data
    })
  }

  extrude() {
    this.data.features.forEach(feature => {
      let coordinates = feature.geometry.coordinates
      let extent = geojsonExtent(feature)
      let center = [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2]
      let s = this.tb.projectedUnitsPerMeter(center[1]);
      let opacity = this.vueInstance.$store.state.landRightOpacity
      let extrusion = this.tb.extrusion({
        coordinates,
        geometryOptions: { curveSegments: 1, bevelEnabled: false, depth: 102 * s },
        materials: new THREE.MeshPhongMaterial({ color: 0x0080ff, transparent: true, opacity, side: THREE.DoubleSide })
      })
      extrusion.name = '宗地产权空间'
      extrusion.setCoords([center[0], center[1], 0]);
      this.tb.add(extrusion)
      this.extrusions.push(extrusion)
    })
  }

  setExtrusionOpacity() {
    let opacity = this.vueInstance.$store.state.landRightOpacity
    this.extrusions.forEach(item => {
      item.traverse(mesh => {
        mesh.isMesh && (mesh.material.opacity = opacity)
      })
    })
  }

  flattern() {
    this.extrusions.forEach(item => {
      this.tb.remove(item)
    })
    this.extrusions = []
  }

  reset() {
    this.vueInstance.$store.commit('patch_land_right', false)
    this.vueInstance.$store.commit('patch_land_info', null)
  }
}

export default LandManager